package com.sunday.fangbeibei.fragment;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.activity.DynamicAddActivity;
import com.sunday.fangbeibei.activity.DynamicMessageActivity;
import com.sunday.fangbeibei.adapter.DynamicAdapter;
import com.sunday.fangbeibei.adapter.DynamicAdapter.OnButtonClickListener;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.BlogInfo;
import com.sunday.fangbeibei.orm.BlogReply;
import com.sunday.fangbeibei.orm.BlogUser;

/**
 * 动态
 * @author 晨曦
 *
 */
public class DynamicFragment extends Fragment implements OnClickListener,OnButtonClickListener,OnRefreshListener2<ListView>,HttpResponseInterface{
	
	private PullToRefreshListView mPullToRefreshListView;
	private ListView listview;
	private ImageView write;
	
	private DynamicAdapter adapter;
	private int pageNo=1;
	
	private EditText comment;
	private TextView btn;
	
	private List<BlogInfo> blogList;
	
	private int currentPosition;
	
	private TextView newmessage;

	private View bottom;
	
	private LinearLayout bottomMenu;
	
	public DynamicFragment(View bottom) {
		// TODO Auto-generated constructor stub
		this.bottom=bottom;
		bottom.setOnClickListener(this);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		loadView();
		loadData();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.dynamic_fragment, null);
	}
	
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		

		RequestParams param=new RequestParams();
		param.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());	
		HttpTool.HttpPost(3, getActivity(), ApplicationConstants.SERVER_URL+"/mobi/blog/getInfoCount", param, this, new TypeToken<BaseResult<Integer>>() {
		}.getType());
		
		
	}

	private void loadView(){
		
		bottomMenu=(LinearLayout) getActivity().findViewById(R.id.bottom_menu);

		mPullToRefreshListView=(PullToRefreshListView) getActivity().findViewById(R.id.listview);
		listview=mPullToRefreshListView.getRefreshableView();
		
		mPullToRefreshListView.setMode(Mode.BOTH);
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多");
		
		mPullToRefreshListView.setOnRefreshListener(this);
		
		newmessage=(TextView) getActivity().findViewById(R.id.new_message);
		newmessage.setOnClickListener(this);
		
		write=(ImageView) getActivity().findViewById(R.id.write);
		write.setOnClickListener(this);
		
		ImageView more=(ImageView) getActivity().findViewById(R.id.more);
		more.setOnClickListener(this);
		
		//c级不能发帖
		if(ApplicationCache.INSTANCE.getUserInfo().getType()==3){
			write.setVisibility(View.INVISIBLE);
			newmessage.setVisibility(View.INVISIBLE);
			more.setVisibility(View.INVISIBLE);
		}
		
		
	}
	
	
	
	private void loadInput(){
		
		bottomMenu.setVisibility(View.GONE);
		
		bottom.setVisibility(View.VISIBLE);
		comment=(EditText) bottom.findViewById(R.id.et_sendmessage);
		btn=(TextView) bottom.findViewById(R.id.btn_send);
		comment.setFocusable(true);
		comment.setFocusableInTouchMode(true);
		comment.requestFocus();
		
		InputMethodManager inputManager =
                    (InputMethodManager)comment.getContext().getSystemService(getActivity().INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(comment, 0);
        btn.setOnClickListener(this);
	}
	
	
	
	
	
	private void loadData(){
		
		
		RequestParams params=new RequestParams();
		params.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());	
		params.add("pageIndex", pageNo+"");
		params.add("pageSize", "10");
		HttpTool.HttpPost(0, getActivity(), ApplicationConstants.SERVER_URL+"/mobi/blog/list", params, this, new TypeToken<BaseResult<List<BlogInfo>>>() {
		}.getType());
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.write:
			Intent in=new Intent(getActivity(), DynamicAddActivity.class);
			startActivity(in);
			break;
		case R.id.btn_send:
			
			if(comment.getText().toString().equals("")){
				Toast.makeText(getActivity(), "评论内容不能为空！", Toast.LENGTH_SHORT).show();
				return;
			}
			
			RequestParams params=new RequestParams();
			params.add("memberId", ApplicationCache.INSTANCE.getUserInfo().getId());
			params.add("blogId", blogList.get(currentPosition).getBlogId());
			params.add("content", comment.getText().toString());
			HttpTool.HttpPost(2, getActivity(), ApplicationConstants.SERVER_URL+"/mobi/blog/comment", params, this, new TypeToken<BaseResult>() {
			}.getType());
			
			break;
		case R.id.more:
			Intent intent=new Intent(getActivity(), DynamicMessageActivity.class);
			intent.putExtra("type", "1");
			startActivity(intent);
			break;
		case R.id.new_message:
			Intent intent2=new Intent(getActivity(), DynamicMessageActivity.class);
			intent2.putExtra("type", "2");
			startActivity(intent2);
			break;
		case R.id.rl_bottom:
			bottomMenu.setVisibility(View.VISIBLE);
			bottom.setVisibility(View.INVISIBLE);
			InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(comment.getWindowToken(), 0); //强制隐藏键盘 
			break;
		}
	}

	//点赞
	@Override
	public void praise(int position) {
		// TODO Auto-generated method stub
		currentPosition=position;
		
		RequestParams params=new RequestParams();
		params.add("memberId", ApplicationCache.INSTANCE.getUserInfo().getId());
		params.add("objId", blogList.get(currentPosition).getBlogId());
		HttpTool.HttpPost(1, getActivity(), ApplicationConstants.SERVER_URL+"/mobi/blog/good", params, this, new TypeToken<BaseResult>() {
		}.getType());
	}
	
	@Override
	public void comment(int position) {
		// TODO Auto-generated method stub
		currentPosition=position;
		loadInput();
		
	}
	
	@Override
	public void share(int position) {
		// TODO Auto-generated method stub
		
		String id=blogList.get(position).getBlogId();
		String url=ApplicationConstants.SERVER_URL+"/mobi/blog/share?blogId="+id;
		
		showShare(url);

	}
	

	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		if(getActivity()==null){
			return;
		}
		switch(requsetCode){
		case 0:
			mPullToRefreshListView.onRefreshComplete();
			BaseResult<List<BlogInfo>> result1=(BaseResult<List<BlogInfo>>) result;
			if(resultStatus){
				if(result1.getResult()==null||result1.getResult().size()==0){
					Toast.makeText(getActivity(), "没有更多数据了！", Toast.LENGTH_SHORT).show();
				}else{
					if(pageNo==1){
						blogList=result1.getResult();
						adapter=new DynamicAdapter(getActivity(),blogList);
						adapter.setOnButtonClickListener(this);
						listview.setAdapter(adapter);
					}else{
						blogList.addAll(result1.getResult());
						adapter.notifyDataSetChanged();
					}
				}
			}
			break;
		case 1:
			BaseResult result2=(BaseResult) result;
			if(resultStatus){
				//Toast.makeText(getActivity(), "操作成功！", Toast.LENGTH_SHORT).show();
				List<BlogUser> users=blogList.get(currentPosition).getFavUser();
				if(result2.getCode()==0){
					//点赞
					BlogUser user=new BlogUser();
					user.setMemberId(ApplicationCache.INSTANCE.getUserInfo().getId());
					user.setMemberName(ApplicationCache.INSTANCE.getUserInfo().getName());
					users.add(user);
					adapter.notifyDataSetChanged();
				}else if(result2.getCode()==1){
					//取消赞
					for(BlogUser user:users){
						if(user.getMemberId().equals(ApplicationCache.INSTANCE.getUserInfo().getId())){
							users.remove(user);
						}
					}
					adapter.notifyDataSetChanged();
				}
			}
			break;
		case 2:
			if(resultStatus){
				bottomMenu.setVisibility(View.VISIBLE);
				bottom.setVisibility(View.INVISIBLE);
				Toast.makeText(getActivity(), "评论成功！", Toast.LENGTH_SHORT).show();
				InputMethodManager inputManager = (InputMethodManager)comment.getContext().getSystemService(getActivity().INPUT_METHOD_SERVICE);
				inputManager.hideSoftInputFromWindow(comment.getWindowToken(), 0);
				BlogReply reply=new BlogReply();
				reply.setContent(comment.getText().toString());
				reply.setMemberName(ApplicationCache.INSTANCE.getUserInfo().getName());
				reply.setMemberId(ApplicationCache.INSTANCE.getUserInfo().getId());
				blogList.get(currentPosition).getReplys().add(reply);
				adapter.notifyDataSetChanged();
				comment.setText("");
			}
			break;
		case 3:
			if(resultStatus){
				BaseResult<Integer> re=(BaseResult<Integer>) result;
				int num=re.getResult();
				if(num>0){
					newmessage.setVisibility(View.VISIBLE);
					newmessage.setText(num+"条新消息");
				}else{
					newmessage.setVisibility(View.GONE);
				}
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		mPullToRefreshListView.onRefreshComplete();
	}


	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		pageNo=1;
		loadData();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		pageNo++;
		loadData();
	}



	private void showShare(String url){
	   ShareSDK.initSDK(getActivity());
	   OnekeyShare oks = new OnekeyShare(); 
	   // 分享时Notification的图标和文字
	   oks.setNotification(R.drawable.icon, getString(R.string.app_name));
	   oks.setText(url);
	   oks.setDialogMode();
	   // 启动分享GUI
	   oks.show(getActivity());
	}


	
	
}
